package com.jadefashion.RedisUtils;

import com.alibaba.fastjson.JSONArray;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jadefashion.pojo.User;
import com.jadefashion.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class RedisCache {

    @Reference
    private  UserService userService;

    @Autowired
    private  RedisTemplate<String, Object> redisTemplate;

    /**
     * 判断redis缓存里是否有数据，如果没有第一次从数据库读取存入redis缓存
     * @param username 根据用户名获取user对象
     * @return 返回用户对象
     */
    public  User redisCache(String username){
        User user = null;
        try {
            //获取redis存储对象
            ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
            //从redis里获取json类型的值
            String userStr = (String) valueOperations.get("user");
            if(userStr==null){
                //缓存没值，从数据库查。
                user = getUserByUsername(username);
            }else {//如果缓存有值
                //把json类型的值转换成User对象
                    user = JSONArray.parseObject(userStr,User.class);
            }
            if(user==null){
                return null;
            }

            //判断当前登录用户是否和redis缓存里的一致
            if(!user.getUsername().equals(username)){
                //如果不相同就更新redis缓存数据
                redisTemplate.delete("user");
              user = getUserByUsername(username);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        //定时清理
        redisTemplate.expire("user",3, TimeUnit.HOURS);
        System.out.println("从redis获取");
        return user;
    }

    public User getUserByUsername(String username){
        try {
            //调用方法从数据库获取对象
            User user=userService.findByUsername(username);
            //把对象转换成json格式
            String json = new ObjectMapper().writeValueAsString(user);
            //把json类型的数据存到redis里
            redisTemplate.opsForValue().set("user",json);
            System.out.println("从数据库获取");
            return user;
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return null;
        }
    }
}
